// 生产token的jwt
const jwt = require('jsonwebtoken')

// 引入 goods 表
const goods = require('../../models/goods')

// 分页查询
list = (req,res)=>{
    // console.log(req.query)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            // token验证成功之后
            goods.find({
                // 模糊查询(有就查，没有就是空)
                goodsname:{$regex: req.query.goodsname ? req.query.goodsname : '',$options:'i'},
                goodsAddress:{$regex: req.query.goodsAddress ? req.query.goodsAddress : '',$options:'i'},
                goodsType:{$regex: req.query.goodsType ? req.query.goodsType : '',$options:'i'},
                // 分页查询
            }).skip((req.query.currentPage - 1) * req.query.pageSize).limit(Number(req.query.pageSize))
            .then(result=>{
                // 这里的查询是为了查总条数
                goods.find({
                    // 模糊查询
                    goodsname:{$regex: req.query.goodsname ? req.query.goodsname : '',$options:'i'},
                    goodsAddress:{$regex: req.query.goodsAddress ? req.query.goodsAddress : '',$options:'i'},
                    goodsType:{$regex: req.query.goodsType ? req.query.goodsType : '',$options:'i'},
                    // 分页查询
                }).countDocuments()
                .then(result2=>{
                    res.json({code:200,data:result,total:result2})
                })
            })
        }
    });
}
// 删除
deleteGoods = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            goods.findByIdAndDelete({_id:req.params.id}).then(result=>{
                res.json({code:200,data:result})
            })
        }
    });
}
// 新增
addGoods = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let _goods = {}
            _goods.goodsname = req.body.goodsname
            _goods.price = req.body.price
            _goods.goodsAddress = req.body.goodsAddress
            _goods.goodsType = req.body.goodsType
            // 这里describe虽然有默认值，但是和传上来的一样，就随便了
            _goods.describe = req.body.describe
            // 这里需要用到默认值
            req.body.goodsImg ? _goods.goodsImg = req.body.goodsImg : ''
            // 这里是数组
            _goods.goodsShowImg = req.body.goodsShowImg
            _goods.goodsDetailsImg = req.body.goodsDetailsImg
            // console.log(_goods)
            new goods(_goods).save().then(result=>{
                // console.log(result)
                res.json({code:200,data:result})
            })
        }
    });
}
// 修改
updateGoods = (req,res)=>{
    // console.log(req.body)
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            let _goods = {}
            _goods.goodsname = req.body.goodsname
            _goods.price = req.body.price
            _goods.goodsAddress = req.body.goodsAddress
            _goods.goodsType = req.body.goodsType
            // 这里describe虽然有默认值，但是和传上来的一样，就随便了
            _goods.describe = req.body.describe
            // 这里需要用到默认值
            req.body.goodsImg ? _goods.goodsImg = req.body.goodsImg : ''
            // 这里是数组
            _goods.goodsShowImg = req.body.goodsShowImg
            _goods.goodsDetailsImg = req.body.goodsDetailsImg
            // console.log(_goods)
            goods.updateOne({_id:req.params.id},{$set:_goods}).then(result=>{
                // 这里返回的是修改之前的值
                res.json({code:200,data:result})
            })
        }
    });
}

// 查询所有的地址
getAllGoodsAddress = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            goods.find({},{goodsAddress:1,_id:0}).then(result=>{
                // 去重
                for(let i=0;i<result.length;i++){
                    for(let j=i+1;j<result.length;j++){
                        if(result[i].goodsAddress === result[j].goodsAddress){
                            result.splice(j,1)
                            j--
                        }
                    }
                }
                res.json({code:200,data:result})
            })
        }
    });
}


// 查询各个地址对应的商品数
getAllGoodsAddressNum = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            goods.find({},{goodsAddress:1,_id:0}).then(result=>{
                // console.log(result)
                // x轴数据
                let xData = []
                // y轴数据
                let yData = []
                let _yData = []
                // result去重
                for(let i=0;i<result.length;i++){
                    for(let j=i+1;j<result.length;j++){
                        if(result[i].goodsAddress === result[j].goodsAddress){
                            result.splice(j,1)
                            j--
                        }
                    }
                }
                // 遍历
                result.map((item,index)=>{
                    // console.log(item)
                    xData.push(item.goodsAddress)

                    goods.find({goodsAddress:item.goodsAddress}).countDocuments().then(result1=>{
                        yData.push(item.goodsAddress+'%'+result1)
                        if(yData.length === xData.length){//这样就保证拿到所有数据
                            // console.log(xData)
                            // console.log(yData)
                            // 上面查出来的顺序有问题，处理一下（因为是异步的）
                            for(let i=0;i<xData.length;i++){
                                for(let j=0;j<yData.length;j++){
                                    // console.log(yData[j])
                                    if(xData[i] === yData[j].split('%')[0]){
                                        _yData.push(yData[j].split('%')[1])
                                    }
                                } 
                            }
                            // console.log(_yData)
                            res.json({code:200,xData:xData,yData:_yData})
                        }
                    })

                    // 同样开启一个异步任务,发出去(这样就保证拿到数据)------------会有错误Cannot set headers after they are sent to the client
                    // setTimeout(()=>{
                        
                    // },100)
                })
            })
        }
    });
}

// 查询各个分类对应的商品数
getAllGoodsTypeNum = (req,res)=>{
    const temp = req.headers.authorization
    const temp1 = temp.split(' ')
    const token = temp1[1]
    jwt.verify(token,'quan_and_huan',(err, authData) => {
        if(err) {
            res.json({code:598,msg:'token失效,请重新登录!'});
        }else{
            goods.find({},{goodsType:1,_id:0}).then(result=>{
                // console.log(result)
                let responseData = []
                // result去重
                for(let i=0;i<result.length;i++){
                    for(let j=i+1;j<result.length;j++){
                        if(result[i].goodsType === result[j].goodsType){
                            result.splice(j,1)
                            j--
                        }
                    }
                }
                // 赋值
                responseData = JSON.parse(JSON.stringify(result))
                // console.log(responseData)
                // 遍历
                responseData.map((item,index)=>{
                    goods.find({goodsType:item.goodsType}).countDocuments().then(result1=>{
                        // console.log(item)
                        item.value = result1
                        item.name = item.goodsType
                        // 只能有value和name
                        delete item.goodsType
                        if(index === result.length-1){
                            // console.log(responseData)
                            res.json({code:200,data:responseData})
                        }
                    })
                })
            })
        }
    });
}

module.exports = {
    list,deleteGoods,addGoods,updateGoods,getAllGoodsAddress,getAllGoodsTypeNum,getAllGoodsAddressNum
}